import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/services.dart';

import 'push_data.dart';

typedef OnReceiveMessage = Function(PushMessage);
typedef OnReceiveNotification = Function(PushNotification);
typedef ApiCallback = Function(bool, Object);

class BpAliyunPush {
  static const MethodChannel _channel = const MethodChannel('bp_aliyun_push');

  static OnReceiveNotification _onReceiveNotification;
  static OnReceiveMessage _onReceiveMessage;

  static Future<String> get platformVersion async {
    return await _channel.invokeMethod('getPlatformVersion');
  }

  static Future<Map<String, dynamic>> get getLaunchNotification async {
    return await _channel.invokeMethod('getLaunchNotification');
  }

  static void onReceive({
    OnReceiveNotification onReceiveNotification,
    OnReceiveMessage onReceiveMessage,
  }) {
    _channel.setMethodCallHandler(_handleMethod);
  }

  static Future<dynamic> _handleMethod(MethodCall call) async {
    print("bp_aliyun_push ${call.method} : ${call.arguments}");
    switch (call.method) {
      case "onReceiverNotification":
        if (_onReceiveNotification != null) {
          var param = call.arguments;
          if (param != null) {
            if (Platform.isIOS) {
              if (param['aps'] != null && param['aps']['alert'] != null) {
                var content = param['aps']['alert'];
                var title = content['title'];
                String body = content['body'];
                param = PushNotification(title, body, param);
              }
            } else {
              param = PushNotification.fromJson(json.decode(param));
            }
          }
          _onReceiveNotification(param);
        }
        break;
      case "onReceiverMessage":
        if (_onReceiveMessage != null) {
          var param = call.arguments;
          if (param != null) {
            param = PushMessage.fromJson(json.decode(param));
          }
          _onReceiveMessage(param);
        }
        break;
    }
  }

  //绑定账号
  static void bindAccount(String account, ApiCallback callback) {
    _channel
        .invokeMethod("bindAccount", account)
        .then((value) => {callback(true, value)})
        .catchError((e) => {callback(false, e)});
  }

  //解绑账号
  static void unbindAccount(ApiCallback callback) {
    _channel
        .invokeMethod("unbindAccount")
        .then((value) => {callback(true, value)})
        .catchError((e) => {callback(false, e)});
  }
}
